package com.jsz.peini.server.thread;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jsz.peini.bean.coupon.CouponGet;
import com.jsz.peini.bean.coupon.CouponHistory;
import com.jsz.peini.bean.coupon.CouponInfo;
import com.jsz.peini.bean.coupon.CouponUser;
import com.jsz.peini.bean.order.OrderInfo;
import com.jsz.peini.bean.order.ScoreHistory;
import com.jsz.peini.bean.user.UserAccount;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.EhcacheUtil;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.SpringContextUtil;
import com.jsz.peini.mapper.coupon.CouponGetMapper;
import com.jsz.peini.mapper.coupon.CouponHistoryMapper;
import com.jsz.peini.mapper.coupon.CouponInfoMapper;
import com.jsz.peini.mapper.coupon.CouponUserMapper;
import com.jsz.peini.mapper.order.OrderInfoMapper;
import com.jsz.peini.mapper.order.ScoreHistoryMapper;
import com.jsz.peini.mapper.user.UserAccountMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;

public class CouponRecvThread extends Thread {
	private static final Logger logger = LoggerFactory.getLogger(CouponRecvThread.class);
	
	private CouponInfoMapper couponInfoMapper;
	
	private CouponUserMapper couponUserMapper;
	
	private CouponGetMapper couponGetMapper;
	
	private UserInfoMapper userInfoMapper;
	
	private UserAccountMapper userAccountMapper;
	
	private OrderInfoMapper orderInfoMapper;
	
	private ScoreHistoryMapper scoreHistoryMapper;
	
	private CouponHistoryMapper couponHistoryMapper;
	
	public void init(){
		this.start();
	}
	
	@Override
	public void run() {
		super.run();
		
		couponInfoMapper = (CouponInfoMapper)SpringContextUtil.getBean(CouponInfoMapper.class);
		
		couponUserMapper = (CouponUserMapper)SpringContextUtil.getBean(CouponUserMapper.class);
		
		couponGetMapper = (CouponGetMapper)SpringContextUtil.getBean(CouponGetMapper.class);
		
		userInfoMapper = (UserInfoMapper)SpringContextUtil.getBean(UserInfoMapper.class);
		
		userAccountMapper = (UserAccountMapper)SpringContextUtil.getBean(UserAccountMapper.class);
		
		orderInfoMapper = (OrderInfoMapper)SpringContextUtil.getBean(OrderInfoMapper.class);
		
		scoreHistoryMapper = (ScoreHistoryMapper)SpringContextUtil.getBean(ScoreHistoryMapper.class);
		
		couponHistoryMapper = (CouponHistoryMapper)SpringContextUtil.getBean(CouponHistoryMapper.class);
		
		while(true)
		{
			try {
				CouponUser couponUser = PeiniUtils.couponUsers.take();
				
				boolean isNull = false;
				boolean isGet = false;
				
				HashMap<String, Object> returnMap = new HashMap<String, Object>();
				if(couponUser.getGetType() == 1){
					//判断是否已经被领光了
					CouponInfo couponInfoNum=couponInfoMapper.getCouponInfoNum(couponUser.getCouponId());
					if (couponInfoNum.getCouponNum()<1) {
						isNull = true;
					}
				}
				
				if(isNull == false){
					
					CouponInfo couponInfo = new CouponInfo();
					couponInfo.setUserId(couponUser.getUserId());
					couponInfo.setId(couponUser.getCouponId());
					couponInfo.setGetType(couponUser.getGetType());
					
					if(couponUser.getGetType() == 1){
						//查询是否已经领用
						List<CouponUser> couponUserList = couponInfoMapper.getCouponUserByUserId(couponInfo);
						if(couponUserList.size() > 0){
							isGet = true;
						}
					}
					
					couponUser.setGetTime(new Date());
					couponUser.setId(UUID.randomUUID().toString().replace("-", ""));
					if(isGet == false){
						switch (couponUser.getGetType()) {
						case 1://活动领取
							CouponHistory chis = new CouponHistory();
							chis.setHisId(UUID.randomUUID().toString().replace("-", ""));
							chis.setCreateTime(new Date());
							chis.setUserId(couponUser.getUserId());
							chis.setOpType(1);
							chis.setIsFinish(1);
							chis.setValNum(1l);
							chis.setHisType(1);
							chis.setParamId(couponUser.getParamId());
							chis.setIsDel(1);
							chis.setCouponId(couponUser.getCouponId());
							couponHistoryMapper.insertSelective(chis);
							
							couponUserMapper.insert(couponUser);
							couponInfo = couponInfoMapper.selectByPrimaryKey(couponUser.getCouponId());
							Long recvNum = couponInfo.getReceivenum() == null ? 0 : couponInfo.getReceivenum();
							couponInfo.setReceivenum(recvNum + 1);
							couponInfoMapper.updateByPrimaryKey(couponInfo);
							//couponInfoMapper.updateCouponInfoByOne(couponUser.getCouponId());
							break;
						case 3://积分
							//判断用户积分余额是否足够
							HashMap<String, Object> paramMap = new HashMap<String, Object>();
							paramMap.put("getType", couponUser.getGetType());
							paramMap.put("couponId", couponUser.getCouponId());
							List<CouponGet> getList = couponGetMapper.selectByCouponIdAndGetType(paramMap);
							if(getList.size() > 0){
								CouponGet couponGet = getList.get(0);
								int getNum = couponGet.getGetNum()==null  ? 0 : couponGet.getGetNum();
								
								//查询用户积分
								UserAccount userAccount = userAccountMapper.selectByUserId(couponUser.getUserId());
								int score = userAccount.getScore()==null  ? 0 : userAccount.getScore();
								
								//如果用户积分小于所需积分不允许领取
								if(getNum > score){
									returnMap.put("resultCode", Constants.FAIL);
									returnMap.put("resultDesc", "非常遗憾，您的积分余额不足，领取失败");
								}else{
									/*couponUserMapper.insert(couponUser);
									couponInfoMapper.updateCouponInfoByOne(couponUser.getCouponId());*/
									
									OrderInfo orderInfo = new OrderInfo();
									orderInfo.setUserId(couponUser.getUserId());
									orderInfo.setOrderStatus(1);
									orderInfo.setAllMoney(getNum);
									orderInfo.setPayMoney(getNum);
									orderInfo.setCouponId(couponUser.getCouponId());
									orderInfo.setOrderTime(new Date());
									orderInfo.setOrderType(2);
									Integer orderId = orderInfoMapper.insertSelective(orderInfo);
									
									String code = "";
									code += orderInfo.getOrderType();
									SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
									code += sdf.format(new Date());
									String codeStr = String.valueOf(orderInfo.getId());
									if(codeStr.length()> 6){
										codeStr = codeStr.substring(codeStr.length()-6);
									}else if(codeStr.length() < 6){
										for (int i = 0; i < 6-codeStr.length(); i++) {
											code += "0";
										}
									}
									code += codeStr;
									orderInfo.setOrderCode(code);
									orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
									
									ScoreHistory his = new ScoreHistory();
									his.setHisId(UUID.randomUUID().toString().replace("-", ""));
									his.setCreateTime(new Date());
									his.setUserId(couponUser.getUserId());
									his.setOpType(0);
									his.setIsFinish(1);
									his.setValNum((long)getNum);
									his.setHisType(3);
									his.setParamId(String.valueOf(couponUser.getCouponId()));
									his.setIsDel(1);
									scoreHistoryMapper.insertSelective(his);
									
									chis = new CouponHistory();
									chis.setHisId(UUID.randomUUID().toString().replace("-", ""));
									chis.setCreateTime(new Date());
									chis.setUserId(couponUser.getUserId());
									chis.setOpType(1);
									chis.setIsFinish(1);
									chis.setValNum(1l);
									chis.setHisType(3);
									chis.setParamId(orderId.toString());
									chis.setIsDel(1);
									chis.setCouponId(couponUser.getCouponId());
									couponHistoryMapper.insertSelective(chis);
									
									userAccount.setScore(getNum);
									userAccount.setPayType(2);
									userAccount.setUserId(couponUser.getUserId());
									userAccountMapper.updateScoreByUserId(userAccount);
									
									if(couponUser.getCouponNum() == 1){
										couponUserMapper.insert(couponUser);
										
										couponInfo = couponInfoMapper.selectByPrimaryKey(couponUser.getCouponId());
										recvNum = couponInfo.getReceivenum() == null ? 0 : couponInfo.getReceivenum();
										couponInfo.setReceivenum(recvNum + 1);
										couponInfoMapper.updateByPrimaryKey(couponInfo);
										
										//couponInfoMapper.updateCouponInfoByOne(couponUser.getCouponId());
									}else{
										int couponNum = couponUser.getCouponNum();
										for (int i = 0; i < couponNum; i++) {
											couponUser.setCouponNum(1);
											couponUserMapper.insert(couponUser);
											//couponInfoMapper.updateCouponInfoByOne(couponUser.getCouponId());
										}
										
										couponInfo = couponInfoMapper.selectByPrimaryKey(couponUser.getCouponId());
										recvNum = couponInfo.getReceivenum() == null ? 0 : couponInfo.getReceivenum();
										couponInfo.setReceivenum(recvNum + couponNum);
										couponInfoMapper.updateByPrimaryKey(couponInfo);
									}
									
									returnMap.put("resultCode", Constants.SUCCESS);
									returnMap.put("resultDesc", "恭喜您成功领取了该优惠券");
								}
							}else{
								returnMap.put("resultCode", Constants.FAIL);
								returnMap.put("resultDesc", "非常遗憾，已经被一抢而光啦");
							}
							break;
						case 2://签到赠送
							if(couponUser.getCouponNum() == 1){
								chis = new CouponHistory();
								chis.setHisId(UUID.randomUUID().toString().replace("-", ""));
								chis.setCreateTime(new Date());
								chis.setUserId(couponUser.getUserId());
								chis.setOpType(1);
								chis.setIsFinish(1);
								chis.setValNum(1l);
								chis.setHisType(2);
								chis.setParamId(couponUser.getParamId());
								chis.setIsDel(1);
								chis.setCouponId(couponUser.getCouponId());
								couponHistoryMapper.insertSelective(chis);
								
								couponUserMapper.insert(couponUser);
								//couponInfoMapper.updateCouponInfoByOne(couponUser.getCouponId());
								couponInfo = couponInfoMapper.selectByPrimaryKey(couponUser.getCouponId());
								recvNum = couponInfo.getReceivenum() == null ? 0 : couponInfo.getReceivenum();
								couponInfo.setReceivenum(recvNum + 1);
								couponInfoMapper.updateByPrimaryKey(couponInfo);
							}else{
								int couponNum = couponUser.getCouponNum();
								for (int i = 0; i < couponNum; i++) {
									chis = new CouponHistory();
									chis.setHisId(UUID.randomUUID().toString().replace("-", ""));
									chis.setCreateTime(new Date());
									chis.setUserId(couponUser.getUserId());
									chis.setOpType(1);
									chis.setIsFinish(1);
									chis.setValNum(1l);
									chis.setHisType(2);
									chis.setParamId(couponUser.getParamId());
									chis.setIsDel(1);
									chis.setCouponId(couponUser.getCouponId());
									couponHistoryMapper.insertSelective(chis);
									
									couponUser.setCouponNum(1);
									couponUserMapper.insert(couponUser);
									//couponInfoMapper.updateCouponInfoByOne(couponUser.getCouponId());
								}
								couponInfo = couponInfoMapper.selectByPrimaryKey(couponUser.getCouponId());
								recvNum = couponInfo.getReceivenum() == null ? 0 : couponInfo.getReceivenum();
								couponInfo.setReceivenum(recvNum + couponNum);
								couponInfoMapper.updateByPrimaryKey(couponInfo);
							}
							break;
						case 4://金币购买；
							
							break;
						case 5://5消费赠送；
							
							break;
						case 6://6任务赠送；
							
							break;
						case 7://7消费最高；
							
							break;
						case 8://任务最多
							
							break;
						case 9://8指定id
							
							break;
						default:
							break;
						}
					}else{
						returnMap.put("resultCode", Constants.FAIL);
						returnMap.put("resultDesc", "您已经领取过该优惠券，不能重复领取");
					}
				}else{
					returnMap.put("resultCode", Constants.FAIL);
					returnMap.put("resultDesc", "非常遗憾，已经被一抢而光啦");
				}
				
				EhcacheUtil.getInstance().put("recvCouponCache", couponUser.getUserId(), returnMap);
				
				Thread.sleep(1);
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
		}
		
	}
}
